package com.cnsugar.ai.face.controller;

import com.alibaba.fastjson.JSONObject;
import com.cnsugar.ai.face.FaceHelper;
import com.cnsugar.ai.face.utils.ImageUtils;
import com.seetaface2.model.SeetaRect;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value="/face")
public class CutImageController {
    private static Logger logger = LoggerFactory.getLogger(CutImageController.class);

    private static final Integer OK_CODE = 200;
    private static final Integer ERROR_CODE = 500;

    /**
     * 人脸抠图接口
     * @param body
     * @param request
     * @return
     */
    @PostMapping("/cut/image")
    public Map<String,Object> cutImage(@RequestBody String body,
                                       HttpServletRequest request){
        JSONObject parseJson= JSONObject.parseObject(body);
        String imgBase64=parseJson.getString("imgBase64");
        Map<String,Object> result = new HashMap<>();
        try{
            logger.info("图片base64内容:{}" + imgBase64);
            List<Map<String,Object>> imgList = new ArrayList<Map<String,Object>>();
            File imgFile = ImageUtils.base64ToFile(imgBase64);
            SeetaRect[] rects = FaceHelper.detect(FileUtils.readFileToByteArray(imgFile));
            if (rects != null) {
                for (SeetaRect rect : rects) {
                    Map<String, Object> imgMap = new HashMap<String, Object>();
                    imgMap.put("x", rect.x);
                    imgMap.put("y", rect.y);
                    imgMap.put("width", rect.width);
                    imgMap.put("height", rect.height);
                    imgList.add(imgMap);
                    logger.info("x="+rect.x+", y="+rect.y+", width="+rect.width+", height="+rect.height);
                }
            }
            result.put("code", OK_CODE);
            result.put("data", imgList);
            result.put("message", "success");
        }catch(Exception e){
            result.put("code", ERROR_CODE);
            result.put("message", e.getMessage());
            logger.error("==============>人脸抠图接口异常,message={}", e);
        }
        return result;
    }


}
